package com.meida.module.bus.provider.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.provider.api.service.SyncOAService;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsOaUtil;
import com.meida.module.bus.provider.mapper.BusMaterialMapper;
import com.meida.module.bus.provider.mapper.BusMaterialPlan100Mapper;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.utils.CommonUtil;
import com.meida.module.bus.provider.utils.LevelNoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 100材料计划表接口实现类
 *
 * @author flyme
 * @date 2020-10-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusMaterialPlan100ServiceImpl extends BaseServiceImpl<BusMaterialPlan100Mapper, BusMaterialPlan100> implements BusMaterialPlan100Service{

    @Autowired
    private SyncSrmService syncSrmService;
    @Autowired
    private BusPurchaseDetailsService busPurchaseDetailsService;
    @Autowired
    private BusPurchaseService busPurchaseService;
    @Autowired
    private BusMaterialSrmService busMaterialSrmService;
    @Autowired
    private BusVersionService busVersionService;
    @Autowired
    private BusMaterialService busMaterialService;
    @Resource
    private BusMaterialMapper busMaterialMapper;
    @Autowired
    private BusMaterialPlan200Service busMaterialPlan200Service;
    @Autowired
    private BusProjectService busProjectService;
    @Autowired
    private PmsOaUtil pmaOaUtil;
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BusMaterialSrmSubService busMaterialSrmSubService;
    @Autowired
    LevelNoUtil levelNoUtil;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private BusMajorService busMajorService;
    @Autowired
    private SyncOAService syncOAService;
    @Autowired
    CommonUtil commonUtil;
    @Autowired
    private PmsApiUtil pmsApiUtil;


    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusMaterialPlan100 bmp, EntityMap extra) {
        Long projectId = TypeUtils.castToLong(bmp.getProjectId());
        BusProject busProject = busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(busProject)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = busProject.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusMaterialPlan100> cq, BusMaterialPlan100 bmp, EntityMap requestMap) {
        if(FlymeUtils.isNotEmpty(requestMap.get("type")) && requestMap.get("type").equals("1")){
            cq.addSelect("bmplan.materialPlanId,bmplan.materialId,bmplan.parentId,bmplan.projectId,bmplan.versionId,bmplan.brandName,bmplan.packageNo," +
                " bmplan.packageName,bmplan.majorCode,bmplan.subjectName,bmplan.materialWbsCode,bmplan.materialCode,bmplan.materialDesc," +
                " bmplan.levelNo,bmplan.contractDesc,bmplan.materialArea,bmplan.materialUse,bmplan.materiaSpecs,bmplan.technicalData,bmplan.materialName,bmplan.costQuantity100,bmplan.costQuantity200,bmplan.measurementUnit,bmplan.loss," +
                " bmplan.majorName,bmplan.planPurchaseCount,bmplan.endPurchaseCount,bmplan.ztPurchaseCount,bmplan.dhPurchaseCount," +
                " bmplan.orderflg,bmplan.status,bmplan.applayStatus,bmplan.planType,bmplan.instructNumber,bmplan.vendorId,bmplan.caseType,bmplan.receivedDate,bmplan.purchaseCount,bmplan.vendorName," +
                " material.conversionUnit,material.mainPrice,material.mainAmount," +
                " material.contractSyntheticalPrice3,material.unitBillQuantity100,material.convertBillQuantity100," +
                " material.unitBillQuantity200,material.convertBillQuantity200,material.convertPurchaseCount");
            cq.addSelect("concat(version.bigVersion,'.',version.smallVerion) as ver,project.projectName,project.projectCode,project.state as projectStatus,user.userName,project.updateTime as versionTime,project.projectId as projectIds ,version.versionId as versionIds");
            cq.isNull("bmplan.parentId");
            cq.notLike("bmplan.materialCode", ApiConstants.MATERIALCODE_MASTER_MARK);
          if(FlymeUtils.isNotEmpty(requestMap.get("applyStatus"))&&FlymeUtils.isNotEmpty(requestMap.get("purseApplayStatus"))){
              cq.eq("bmplan.purseApplayStatus", requestMap.get("purseApplayStatus"));
              cq.eq("bmplan.applayStatus", requestMap.get("applyStatus"));
          }
          }else{
            cq.addSelect("bmplan.materialPlanId,bmplan.materialId,bmplan.parentId,bmplan.projectId,bmplan.versionId,bmplan.brandName,bmplan.packageNo," +
                " bmplan.packageName,bmplan.majorCode,bmplan.subjectName,bmplan.materialWbsCode,bmplan.materialCode,bmplan.materialDesc," +
                " bmplan.levelNo,bmplan.contractDesc,bmplan.materialArea,bmplan.materialUse,bmplan.materiaSpecs,bmplan.technicalData,bmplan.materialName,bmplan.costQuantity100,bmplan.costQuantity200,bmplan.measurementUnit,bmplan.loss," +
                " bmplan.majorName,bmplan.planPurchaseCount,bmplan.endPurchaseCount,bmplan.ztPurchaseCount,bmplan.dhPurchaseCount,bmplan.purchaseCount," +
                "bmplan.receivedDate,bmplan.orderflg,bmplan.status,bmplan.applayStatus,bmplan.planType,bmplan.instructNumber,bmplan.vendorId,bmplan.vendorName,bmplan.caseType," +
                "material.conversionUnit,material.mainPrice,material.mainAmount," +
                "material.contractSyntheticalPrice3,material.unitBillQuantity100,material.convertBillQuantity100," +
                "material.unitBillQuantity200,material.convertBillQuantity200,material.convertPurchaseCount");
            cq.addSelect("concat(version.bigVersion,'.',version.smallVerion) as ver,project.projectName,project.projectCode,project.state as projectStatus,user.userName,project.updateTime as versionTime,project.projectId as projectIds ,version.versionId as versionIds");
        }
        cq.createJoin(BusProject.class).setMainField("projectId").setJoinField("projectId");
        cq.createJoin(BusVersion.class).setMainAlias("project").setMainField("versionId").setJoinField("versionId");
        cq.createJoin(BusMaterial.class).setMainField("materialId").setJoinField("materialId");
        cq.createJoin(BaseUser.class).setMainAlias("version").setJoinField("userId").setJoinField("userId");
        if (FlymeUtils.isNotEmpty(requestMap.get("projectId"))) {
            cq.eq("bmplan.projectId", requestMap.get("projectId"));
        } else {
            cq.groupBy("project.versionId");
        }
//            cq.addSelect("supplier.supplierName as vendorId, dictdata.dicDataTitle as  caseType");
//            cq.createJoin(BusSupplier.class).setMainField("vendorId").setJoinField("supplierId");
//            cq.createJoin(SysDictData.class).setMainField("caseType").setJoinField("dicDataValue");
            Long userId = OpenHelper.getUserId();
            List<String> userMajorList = busMajorService.getUserMajors(userId);
            if (userMajorList.size() > 0) {
                if (!userMajorList.contains("P99")) {
                    cq.in("bmplan.majorCode", userMajorList);
                }
            }
            cq.like("project.projectName", requestMap.get("projectName"));
        cq.like("project.projectCode", requestMap.get("projectCode"));
        cq.like("bmplan.packageNo", requestMap.get("packageNo"));
        cq.like("bmplan.packageName", requestMap.get("packageName"));
        cq.like("bmplan.majorName", requestMap.get("majorName"));
        cq.like("bmplan.majorCode", requestMap.get("majorCode"));
        cq.like("bmplan.packageName", requestMap.get("packageName"));
        cq.like("bmplan.materialWbsCode", requestMap.get("materialWbsCode"));
        cq.like("bmplan.materialCode", requestMap.get("materialCode"));
        cq.like("bmplan.materialName", requestMap.get("materialName"));
        cq.like("bmplan.levelNo", requestMap.get("levelNo"));
        cq.like("bmplan.subjectName", requestMap.get("subjectName"));
        cq.like("bmplan.materialArea", requestMap.get("materialArea"));
        cq.like("bmplan.materialUse", requestMap.get("materialUse"));
        cq.eq("bmplan.materialId", requestMap.get("materialId"));
        if(FlymeUtils.isNotEmpty(requestMap.get("versionId"))){
            cq.eq("bmplan.versionId",requestMap.get("versionId"));
        }
        if(FlymeUtils.isNotEmpty(requestMap.get("planType"))){
//            //修正变更
//            if(requestMap.get("planType").equals("1")){
//                cq.isNull("bmplan.instructNumber");
//                cq.isNotNull("bmplan.parentId");
//            }
//            //追加变更
//            if(requestMap.get("planType").equals("2")){
//                cq.isNotNull("bmplan.instructNumber");
//                cq.isNotNull("bmplan.parentId");
//            }
            cq.eq("bmplan.planType",requestMap.get("planType"));
        }
        if(FlymeUtils.isNotEmpty(requestMap.get("versionStatus"))){
           cq.eq("bmplan.versionStatus",requestMap.get("versionStatus"));
        }
        if(FlymeUtils.isNotEmpty(requestMap.get("applayStatus"))){
            cq.eq("bmplan.applayStatus",requestMap.get("applayStatus"));
        }
        cq.ge("bmplan.status", "1");
        cq.orderByAsc("bmplan.levelNo");
//        cq.orderByDesc("bmplan.updateTime");
        return ResultBody.ok();
    }

    @Override
    public ResultBody updateMaterial(Long projectId, Long versionId, BusPurchase purchase){
        BusProject busProject = busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(busProject)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = busProject.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        if (FlymeUtils.isNotEmpty(purchase.getDetails())) {
            List<BusPurchaseDetails> bLis = new ArrayList<>();
            List<BusMaterialPlan100> pnlist = new ArrayList<>();
            List<BusMaterialPlan100> purselist = new ArrayList<>();
            for (BusPurchaseDetails se : purchase.getDetails()) {
                BusMaterialPlan100 plan100 = getById(se.getMaterialId());
                if (FlymeUtils.isNotEmpty(plan100)) {
                    if (FlymeUtils.isNotEmpty(se.getPurchaseNum())) {
                        if (se.getPurchaseNum().compareTo(plan100.getEndPurchaseCount()) > 0) {
                            return ResultBody.failed("本次采购量不能大于剩余采购量");
                        }
                        plan100.setPurchaseCount(se.getPurchaseNum());//本次采购量
                        plan100.setZtPurchaseCount(plan100.getZtPurchaseCount().add(se.getPurchaseNum()));//在途数量=本次采购量+原材料明细在途数量
                    } else {
                        return ResultBody.failed("采购量不为空");
                    }
                    plan100.setEndPurchaseCount(plan100.getEndPurchaseCount().subtract(se.getPurchaseNum()));//剩余采购计划量
                    if (FlymeUtils.isNotEmpty(se.getReceivedDate())) {
                        String date = se.getReceivedDate().substring(0, 10);
                        plan100.setReceivedDate(DateUtils.formatDate(date));
                        se.setReceivedDate(DateUtils.formatDate(date));
                    } else {
                        return ResultBody.failed("计划到货时间不能为空");
                    }
                    plan100.setDhPurchaseCount(BigDecimal.ZERO);
                    plan100.setApplayStatus(0);
                    plan100.setOrderflg("0");//订单下达
                    if (FlymeUtils.isNotEmpty(se.getVendorName())) {
                        plan100.setVendorName(se.getVendorName());
                    }
                    if (FlymeUtils.isNotEmpty(se.getDocumentType())) {
                        plan100.setCaseType(se.getDocumentType());
                    }
//                    else{
//                        return ResultBody.failed("单据类型不能为空");
//                    }
                    pnlist.add(plan100);

                    // 在途数量
                    se.setOnLineNum(se.getPurchaseNum());
                    // 到货数量
                    se.setReceiveNum(BigDecimal.ZERO);
                }
            }

            if (FlymeUtils.isNotEmpty(pnlist)) {
                boolean cd = saveOrUpdateBatch(pnlist);
            }
            purselist.addAll(pnlist);
            BaseUser user = baseUserService.getUserById(OpenHelper.getUserId());
            boolean a = busPurchaseDetailsService.saveBatch(purchase.getDetails());
            boolean b = busPurchaseService.save(purchase);
            Map applyMap=new HashMap();
            applyMap.put("plan100detail",pnlist);
            applyMap.put("purchase",purchase);
            applyMap.put("purchaseDetail",purchase.getDetails());
            updatepurseApplayStatus(projectId,purselist);//更新状态为审核中
            int status= syncOAService.approval(applyMap, "/approvl/purseDetail100", OpenHelper.getUserName(), ApiConstants.ENGINEER_APPROVAL_WZ_REQ ,projectId.toString());
            if(status==1){
                return ResultBody.ok("材料审批发送，成功等待审批");
            }
         }
        return ResultBody.ok();
    }
    @Override
    public ResultBody goPurseSuccess(Integer checkState, Long projectId, List<BusMaterialPlan100> plan100List,BusPurchase purchase, String userNm){

        if (checkState == ApiConstants.APPROVAL_REJECT) {//审核驳回
           //释放本彩采购量到计划采购量中
            for (BusMaterialPlan100 plan100 :plan100List){
                plan100.setEndPurchaseCount(plan100.getPurchaseCount().add(plan100.getEndPurchaseCount()));
                plan100.setZtPurchaseCount(plan100.getZtPurchaseCount().subtract(plan100.getPurchaseCount()));
                plan100.setPurseApplayStatus(1);
                plan100.setApplayStatus(2);
            }
            saveOrUpdateBatch(plan100List);
        }
        //审批通过
        if (checkState == ApiConstants.APPROVAL_SUCCESS) {
            try {
                //释放本彩采购量到计划采购量中
                for (BusMaterialPlan100 plan100 :plan100List){
                    plan100.setPurseApplayStatus(1);
                    plan100.setApplayStatus(2);
                }
                saveOrUpdateBatch(plan100List);
                //审核通过发起srm
                int orderRequest = syncSrmService.materialRequest(purchase, userNm);
                if (orderRequest == 0) {
                    return ResultBody.ok("材料申请成功", purchase);
                } else {
                    return ResultBody.ok("材料申请失败");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ResultBody.ok();
    }
    @Override
    public Boolean updatepurseApplayStatus(Long projectId, List<BusMaterialPlan100> plan100s) {
        if(FlymeUtils.isNotEmpty(plan100s)) {
            for (BusMaterialPlan100 se : plan100s) {
                se.setPurseApplayStatus(1);
                se.setApplayStatus(1);
            }
        }
        return saveOrUpdateBatch(plan100s);
    }



    @Override
    public boolean isOpentorVersStatus(Long projectId, String versionType) {
        BusProject project = busProjectService.getById(projectId);
        BusVersion latestVersion = busVersionService.getLatestVersion(projectId, 1);
        if (FlymeUtils.isNotEmpty(latestVersion)) {
            Integer bigversion = TypeUtils.castToInt(latestVersion.getBigVersion());
            if (bigversion > Integer.parseInt(versionType)) {
                return false;
            } else {
                return true;
            }
        }
        return true;
    }

    @Override
    public List<Long> getPlanIds(Long projectId) {
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery<BusMaterialPlan100>(BusMaterialPlan100.class);
        cq.select("materialPlanId");
        cq.eq("status", 1);
//        cq.notIn("applayStatus", "1");
//        cq.eq("ztPurchaseCount", 0);
        cq.isNull("parentId");
        return selectLongs(cq);
    }

    private List<Long> getexceplPlanIds(Long projectId) {
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery<BusMaterialPlan100>(BusMaterialPlan100.class);
        cq.select("materialPlanId");
        cq.eq("status", 1);
        cq.isNull("parentId");
        return selectLongs(cq);
    }

    @Override
    public List<Long> getinitPlanIds(Long projectId) {
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery<BusMaterialPlan100>(BusMaterialPlan100.class);
        cq.select("materialPlanId");
        cq.eq("status", 0);
        return selectLongs(cq);
    }

    @Override
    public List<EntityMap> initDataplans(Map map) {
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery(BusMaterialPlan100.class);
        cq.addSelect(BusMaterialPlan100.class, "*");
        cq.addSelect(BusProject.class, "projectCode", "projectName");
        cq.addSelect(BusMaterial.class, "conversionUnit,mainPrice,mainAmount," +
            "contractSyntheticalPrice3,unitBillQuantity100,convertBillQuantity100," +
            "unitBillQuantity200,convertBillQuantity200");
        cq.like("project.projectCode", map.get("projectCode"));
        cq.like("project.projectName", map.get("projectName"));
        cq.like("bmplan.majorName", map.get("majorName"));
        cq.like("bmplan.majorCode", map.get("majorCode"));
        cq.like("bmplan.packageName", map.get("packageName"));
        cq.like("bmplan.packageNo", map.get("packageNo"));
        cq.like("bmplan.materialWbsCode", map.get("materialWbsCode"));
        cq.like("bmplan.materialName", map.get("materialName"));
        cq.like("bmplan.levelNo", map.get("levelNo"));
        cq.like("bmplan.subjectName", map.get("subjectName"));
        cq.like("bmplan.materialArea", map.get("materialArea"));
        Long userId = OpenHelper.getUserId();
        List<String> userMajorList = busMajorService.getUserMajors(userId);
        if (userMajorList.size() > 0) {
            if (!userMajorList.contains("P99")) {
                cq.in("bmplan.majorCode", userMajorList);
            }
        }
        cq.ge("bmplan.status", "1");
        cq.eq("project.projectId", map.get("projectId"));
        cq.eq("bmplan.versionId", map.get("versionId"));
        // cq.orderByAsc("bmplan.createTime");
        cq.orderByAsc("bmplan.levelNo");
        cq.createJoin(BusProject.class).setMainField("projectId").setJoinField("projectId");
        cq.createJoin(BusMaterial.class).setMainField("materialId").setJoinField("materialId");
        return selectEntityMap(cq);
    }

    @Override
    public List<EntityMap> initPurchseDataplans(Map map) {
        List<Long> materialPlanIds = new ArrayList<>();
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery(BusMaterialPlan100.class);
        cq.addSelect(BusMaterialPlan100.class, "materialPlanId", "materialId", "parentId", "projectId", "versionId", "brandName", "packageNo",
            "packageName", "majorCode", "subjectName", "materialWbsCode", "materialCode", "materialDesc", "vendorName", "caseType",
            " levelNo", "contractDesc", "materialArea", "materialUse", "materiaSpecs", "technicalData", "materialName", "costQuantity100", "costQuantity200", "measurementUnit", "loss",
            " majorName", "planPurchaseCount", "endPurchaseCount", "ztPurchaseCount", "dhPurchaseCount", "purchaseCount", "receivedDate", "orderflg", "status", "applayStatus", "planType");
        cq.addSelect(BusProject.class, "projectCode", "projectName");
        cq.addSelect(BusMaterial.class, "conversionUnit", "mainPrice", "mainAmount",
            "contractSyntheticalPrice3", "unitBillQuantity100", "convertBillQuantity100",
            "unitBillQuantity200", "convertBillQuantity200");
//        cq.addSelect("supplier.supplierName as vendorId, dictdata.dicDataTitle as  caseType");
        cq.createJoin(BusProject.class).setMainField("projectId").setJoinField("projectId");
        cq.createJoin(BusMaterial.class).setMainField("materialId").setJoinField("materialId");
//        cq.createJoin(BusSupplier.class).setMainField("vendorId").setJoinField("supplierId");
//        cq.createJoin(SysDictData.class).setMainField("caseType").setJoinField("dicDataValue");
        cq.like("bmplan.packageNo", map.get("packageNo"));
        cq.like("bmplan.packageName", map.get("packageName"));
        cq.like("bmplan.majorName", map.get("majorName"));
        cq.like("bmplan.majorCode", map.get("majorCode"));
        cq.like("bmplan.packageName", map.get("packageName"));
        cq.like("bmplan.packageNo", map.get("packageNo"));
        cq.like("bmplan.materialWbsCode", map.get("materialWbsCode"));
        cq.like("bmplan.materialName", map.get("materialName"));
        cq.like("bmplan.levelNo", map.get("levelNo"));
        cq.like("bmplan.subjectName", map.get("subjectName"));
        cq.like("bmplan.materialArea", map.get("materialArea"));
        cq.like("bmplan.materialUse", map.get("materialUse"));
        Long userId = OpenHelper.getUserId();
        List<String> userMajorList = busMajorService.getUserMajors(userId);
        if (userMajorList.size() > 0) {
            if (!userMajorList.contains("P99")) {
                cq.in("bmplan.majorCode", userMajorList);
            }
        }
        cq.eq("bmplan.projectId", map.get("projectId"));
        cq.ge("bmplan.status", "1");
        cq.isNull("bmplan.parentId");
        cq.notLike("bmplan.materialCode", ApiConstants.MATERIALCODE_MASTER_MARK);
        cq.orderByAsc("bmplan.levelNo");
//        cq.orderByDesc("bmplan.updateTime");
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody importOnUpdateplan100Data(MultipartFile file, Map params) {
        int i=1;
        try {
            List<BusMaterialPlan100> busMaterialPlan100List = new ArrayList<>();
            List<BusMaterial> busMaterials = new ArrayList<>();
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            Long projectId = Long.parseLong(params.get("projectId").toString());
            BusProject project = busProjectService.getById(projectId);
            if (FlymeUtils.isEmpty(project)) {
                return ResultBody.failed("项目信息不存在");
            }
            Integer state = project.getState();
            if (state == 1) {
                return ResultBody.failed("项目已锁定");
            }
            BusVersion version = busVersionService.getLatestVersion(projectId, 1);
            BusVersion version_new = new BusVersion();
            BeanUtils.copyProperties(version, version_new);
            String smallVerion = version_new.getSmallVerion();
            Integer small = TypeUtils.castToInt(smallVerion) + 1;
            if (small < 10) {
                smallVerion = "0" + small;
            } else {
                smallVerion = TypeUtils.castToString(small);
            }
            Long versionId = IdWorker.getId();
            version_new.setVersionId(versionId);
            version_new.setSmallVerion(smallVerion);
            version_new.setProjectId(projectId);
            version_new.setState(0);
            version_new.setVersionType(1);
            version_new.setUserId(OpenHelper.getUserId());
            List<Map<Object, Object>> ExcelList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, importParams);
            if(commonUtil.ckLevelNo(projectId, ApiConstants.FB_PLANDATA_100, ExcelList)) {
                return ResultBody.failed("存在重复的层级号");
            }
            System.out.println(ExcelList.size());
            project.setVersionId(versionId);
            project.setUserId(OpenHelper.getUserId());

            ResultBody resultBody = pmsApiUtil.chkImpExcelContentForPlanData(ExcelList, ApiConstants.WZ_PLANDATA);
            if(!resultBody.isOk()) {
                return resultBody;
            }

            for (Map<Object, Object> objectObjectMap : ExcelList) {
                i++;
                objectObjectMap.forEach((k, v) -> {
                    if (v == null || v.equals("null")) {
                        v = "";
                        objectObjectMap.put(k, v);
                    }
                });
                BusMaterialPlan100 plan100s = new BusMaterialPlan100();
                BusMaterial busMaterial = new BusMaterial();
                Long materialplan100Id = TypeUtils.castToLong(objectObjectMap.get("材料id"));
                String isAdd = String.valueOf(objectObjectMap.get("是否新增"));
                if (isAdd.equals("否")) {
                    continue;
                }
                Long meaterialId = IdWorker.getId();
                BigDecimal costQuantity100 = BigDecimal.ZERO;
                if(FlymeUtils.isNotEmpty(objectObjectMap.get("100预算成本工程量").toString())){
                    costQuantity100 = BigDecimal.valueOf(Double.parseDouble(objectObjectMap.get("100预算成本工程量").toString()));
                }
//                if (ObjectUtils.isEmpty(objectObjectMap.get("层级号"))) {
//                    return ResultBody.failed("请查看层级号");
//                }
//                if (!objectObjectMap.get("层级号").toString().substring(0, 5).equals(obje
//                ctObjectMap.get("工程包代码").toString())) {
//                    return ResultBody.failed("层级号与工程包代码不一致");
//                }
                String majorCode = String.valueOf(objectObjectMap.get("专业代码"));
                String majorName = String.valueOf(objectObjectMap.get("专业名称"));
                String projectCode = String.valueOf(objectObjectMap.get("工程包代码"));
                String projectName = String.valueOf(objectObjectMap.get("工程包名称"));
                String materialCode = String.valueOf(objectObjectMap.get("物料代码"));
                String materialWbsCode = String.valueOf(objectObjectMap.get("物料wbs代码"));
                String materialName = String.valueOf(objectObjectMap.get("设备、材料名称"));
                String materiaSpecs = String.valueOf(objectObjectMap.get("型号/规格"));
                String technicalData = String.valueOf(objectObjectMap.get("技术参数或技术说明"));
                String subjectName = String.valueOf(objectObjectMap.get("科目名称"));
                String levelNo = String.valueOf(objectObjectMap.get("层级号"));
                String materialDesc = String.valueOf(objectObjectMap.get("材料项目描述"));
                String contractDesc = String.valueOf(objectObjectMap.get("对外合同清单描述"));
                String materialArea = String.valueOf(objectObjectMap.get("区域"));
                String materialUse = String.valueOf(objectObjectMap.get("系统"));
                String measurementUnit = String.valueOf(objectObjectMap.get("计量单位"));
                String conversionUnit = String.valueOf(objectObjectMap.get("换算单位"));
                String brandName = String.valueOf(objectObjectMap.get("品牌"));
                String remark = String.valueOf(objectObjectMap.get("备注"));

                BigDecimal loss = BigDecimal.ZERO;
                if (FlymeUtils.isNotEmpty(objectObjectMap.get("损耗"))) {
                    loss = BigDecimal.valueOf(Double.parseDouble(objectObjectMap.get("损耗").toString()));
                }
                //判断是否为父子关系的新增
                if (isAdd.equals("是")) {
                    if (FlymeUtils.isNotEmpty(materialplan100Id)) {
                        BusMaterialPlan100 plan100ls = getById(materialplan100Id);
                        BusMaterial material = busMaterialService.getById(plan100ls.getMaterialId());
                        BeanUtils.copyProperties(material, busMaterial);
                        busMaterial.setMaterialId(meaterialId);
                        busMaterial.setParentId(material.getMaterialId());
                        BeanUtils.copyProperties(plan100ls, plan100s);
                        plan100s.setPlanPurchaseCount(costQuantity100.multiply(loss));
                        plan100s.setEndPurchaseCount(costQuantity100.multiply(loss));
                        if (FlymeUtils.isNotEmpty(plan100s.getParentId())) {
                            plan100s.setParentId(plan100s.getParentId());
                        } else {
                            plan100s.setParentId(materialplan100Id);
                        }
                        plan100s.setCostQuantity100(costQuantity100);
                        plan100s.setCreateTime(DateUtils.getNowDateTime());
                        plan100s.setUpdateTime(DateUtils.getNowDateTime());
                        plan100s.setMaterialPlanId(IdWorker.getId());
                        plan100s.setMaterialId(meaterialId);
                        plan100s.setVersionStatus(0);
                        plan100s.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);//待审核
                        if(FlymeUtils.isNotEmpty(params.get("dataType"))){
                            plan100s.setPlanType(Integer.parseInt(params.get("dataType").toString()));
                        }
                        plan100s.setVersionId(versionId);
                        busMaterialPlan100List.add(plan100s);
                        busMaterials.add(busMaterial);
                    } else {
                        busMaterial.setMaterialId(meaterialId);
                        busMaterial.setProjectId(projectId);
                        busMaterial.setParentId(0L);
                        busMaterial.setLoss(loss);
                        plan100s.setMaterialPlanId(IdWorker.getId());
                        plan100s.setOrderflg("0");//初始化开口订单状态
                        plan100s.setStatus(1);//未转存100
                        plan100s.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);//待审核状态
                        if(FlymeUtils.isNotEmpty(params.get("dataType"))){
                            plan100s.setPlanType(Integer.parseInt(params.get("dataType").toString()));
                        }
                        plan100s.setMaterialId(meaterialId);
                        plan100s.setProjectId(projectId);
                        plan100s.setVersionId(versionId);
                        plan100s.setMajorName(majorName);
                        plan100s.setMajorCode(majorCode);
                        plan100s.setPackageName(projectName);
                        plan100s.setVersionStatus(0);
                        plan100s.setPackageNo(projectCode);
                        plan100s.setLevelNo(levelNo);
                        plan100s.setMaterialWbsCode(materialWbsCode);
                        plan100s.setMaterialDesc(materialDesc);
                        plan100s.setMaterialName(materialName);
                        plan100s.setMaterialCode(materialCode);
                        plan100s.setSubjectName(subjectName);
                        plan100s.setContractDesc(contractDesc);
                        plan100s.setMaterialArea(materialArea);
                        plan100s.setMaterialUse(materialUse);
                        plan100s.setCostQuantity100(costQuantity100);
                        plan100s.setCostQuantity200(BigDecimal.ZERO);
                        plan100s.setMeasurementUnit(measurementUnit);
                        plan100s.setBrandName(brandName);
                        plan100s.setRemark(remark);
                        plan100s.setLoss(loss);
                        plan100s.setTechnicalData(technicalData);
                        plan100s.setMateriaSpecs(materiaSpecs);
                        plan100s.setLevelNo(levelNo);
                        plan100s.setZtPurchaseCount(BigDecimal.ZERO);
                        plan100s.setOrderflg("0");
                        plan100s.setDhPurchaseCount(BigDecimal.ZERO);
                        plan100s.setPurchaseCount(BigDecimal.ZERO);
                        plan100s.setPlanPurchaseCount(costQuantity100.multiply(loss));
//                        plan100s.setDisplayplanPurchaseCount(costQuantity100.multiply(loss));
                        plan100s.setEndPurchaseCount(costQuantity100.multiply(loss));
                        busMaterialPlan100List.add(plan100s);
                        busMaterials.add(busMaterial);
                    }
                }
            }
            if (busMaterialPlan100List.size() > 0) {
                busMaterialService.saveBatch(busMaterials);
                saveBatch(busMaterialPlan100List);
                busProjectService.saveOrUpdate(project);//更新项目版本
                busVersionService.saveOrUpdate(version_new);//更新此次操作版本
                return ResultBody.ok("导入成功");
            }else{
                return ResultBody.failed("当前excel没有要处理的数据，请查看");
            }
        } catch (Exception e) {
            System.out.println("请核对第"+i+"数据");
            e.printStackTrace();
            return ResultBody.failed("导入失败"+"请核对第"+i+"数据");
        }
    }

    @Override
    public ResultBody import100PurseDetail(MultipartFile file, Map params) {
        try {
            List<BusMaterialPlan100> busMaterialPlan100List = new ArrayList<>();
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            List<Map<Object, Object>> ExcelList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, importParams);
            int i = 1;
            for (Map<Object, Object> objectObjectMap : ExcelList) {
                if(!objectObjectMap.get("计量单位").equals(objectObjectMap.get("物料单位"))) {
                    return ResultBody.failed("存在计量单位与物料单位不一致的材料申请");
                }

                EntityMap entityMap = new EntityMap();
                objectObjectMap.forEach((k, v) -> {
                    if (v == null || v.equals("null")) {
                        v = "";
                        objectObjectMap.put(k, v);
                    }
                });
                Long materialplan100Id = TypeUtils.castToLong(objectObjectMap.get("编号"));
                BusMaterialPlan100 plan100 = getById(materialplan100Id);
                BusProject project = busProjectService.getById(plan100.getProjectId());
                if (FlymeUtils.isEmpty(project)) {
                    return ResultBody.failed("项目信息不存在");
                }
                Integer state = project.getState();
                if (state == 1) {
                    return ResultBody.failed("项目已锁定");
                }
                String isUpdate = String.valueOf(objectObjectMap.get("是否修改"));
                if (isUpdate.equals("否")) {
                    continue;
                }
                BigDecimal purchaseCount = TypeUtils.castToBigDecimal(objectObjectMap.get("本次采购量"));
                String receivedDate = TypeUtils.castToString(objectObjectMap.get("计划到货时间"));
                String caseType = TypeUtils.castToString(objectObjectMap.get("单据类型"));
                String vendorName = TypeUtils.castToString(objectObjectMap.get("班组"));
                if (FlymeUtils.isEmpty(purchaseCount)) {
                    return ResultBody.failed("请核对第" + i + "行本次采购量为空");
                }
                if (FlymeUtils.isEmpty(receivedDate)) {
                    return ResultBody.failed("请核对第" + i + "行计划到货时间为空");
                }
                plan100.setVendorName(vendorName);
                plan100.setPurchaseCount(purchaseCount);
                plan100.setCaseType(caseType);
                plan100.setReceivedDate(DateUtils.formatDate(receivedDate));
                busMaterialPlan100List.add(plan100);
                i++;
            }
            if(busMaterialPlan100List.size()>0){
                String key = String.valueOf(IdWorker.getId());
                redisUtils.setList(key, busMaterialPlan100List, 3600);
                return ResultBody.ok(key);
            }else{
                return ResultBody.failed("当前excel没有要处理的数据");
            }
        } catch (Exception e) {
            return ResultBody.failed("导入失败");
        }
    }

    @Override
    public ResultBody copyAndUpdateplan(Map map) {
        String copyDataStr = (String) map.get("copyDataStr");
        Long projectId = TypeUtils.castToLong(map.get("projectId"));
        BusProject project = busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        Integer type = TypeUtils.castToInt(map.get("type"));
        BusVersion latestVersion = busVersionService.getLatestVersion(projectId, 1);
        if (FlymeUtils.isEmpty(latestVersion)) {
            return ResultBody.failed("无版本信息");
        }
        BusVersion newBusVersion = new BusVersion();
        BeanUtils.copyProperties(latestVersion, newBusVersion);
        String smallVerion = newBusVersion.getSmallVerion();
        Integer small = TypeUtils.castToInt(smallVerion) + 1;
        if (small < 10) {
            smallVerion = "0" + small;
        } else {
            smallVerion = TypeUtils.castToString(small);
        }
        newBusVersion.setSmallVerion(smallVerion);
        Long versionId = IdWorker.getId();
        newBusVersion.setUserId(OpenHelper.getUserId());
        newBusVersion.setVersionId(versionId);
        newBusVersion.setCreateTime(DateUtils.getNowDateTime());
        newBusVersion.setState(0);//审核版本
        newBusVersion.setVersionType(1);//材料版本
        newBusVersion.setProjectId(projectId);
        busVersionService.saveOrUpdate(newBusVersion);
        project.setVersionId(versionId);
        project.setUserId(OpenHelper.getUserId());
        busProjectService.saveOrUpdate(project);
        //提交过来的数据
        List<BusMaterialPlan100> busMaterialPlan100List = JSON.parseArray(copyDataStr, BusMaterialPlan100.class);
        //原始项目中的材料
        List<BusMaterial> bBusMaterialList = new ArrayList<>();
        for (BusMaterialPlan100 busMaterialPlan100 : busMaterialPlan100List) {
            //100成本工程量
            busMaterialPlan100.setCostQuantity100(busMaterialPlan100.getCostQuantity100());
            //计算变更后的量
            BusMaterial busMaterial = busMaterialService.getById(busMaterialPlan100.getMaterialId());
            //复制生成一条新的材料
            BusMaterial newl = new BusMaterial();
            BeanUtils.copyProperties(busMaterial, newl);
            Long materialId = IdWorker.getId();
            newl.setMaterialId(materialId);
            newl.setParentId(busMaterialPlan100.getMaterialId());
            newl.setProjectId(projectId);
            //计算剩余采购量跟剩余采购量
            busMaterialPlan100.setOrderflg("0");//是否有开口订单 0否
            //采购计划数量
            busMaterialPlan100.setPlanPurchaseCount(busMaterialPlan100.getCostQuantity100().multiply(busMaterialPlan100.getLoss()));
            //显示量100
            busMaterialPlan100.setDisplayplanPurchaseCount(busMaterialPlan100.getCostQuantity100().multiply(busMaterialPlan100.getLoss()));
            //剩余采购量
            busMaterialPlan100.setEndPurchaseCount(busMaterialPlan100.getCostQuantity100().multiply(busMaterialPlan100.getLoss()));
//            newl.setMaterialId(materialId);
//            newl.setProjectId(projectId);
//            newl.setMainPrice(busMaterial.getMainPrice());
//            newl.setMainPrice1(busMaterial.getMainPrice2());
//            newl.setMainPrice2(busMaterial.getMainPrice3());
//            newl.setMainPrice3(busMaterial.getMainPrice3());
//            newl.setInstallPrice(busMaterial.getInstallPrice());
//            newl.setInstallPrice1(busMaterial.getInstallPrice1());
//            newl.setInstallPrice2(busMaterial.getInstallPrice2());
//            newl.setInstallPrice3(busMaterial.getInstallPrice3());
//            newl.setMainAmount(busMaterial.getMainPrice().multiply(busMaterialPlan100.getCostQuantity100()));//成本主材费
//            newl.setMainAmount1(busMaterial.getMainPrice1().multiply(busMaterialPlan100.getCostQuantity100()));
//            newl.setMainAmount2(busMaterial.getMainPrice2().multiply(busMaterialPlan100.getCostQuantity100()));
//            newl.setMainAmount3(busMaterial.getMainPrice3().multiply(busMaterialPlan100.getCostQuantity100()));
//            newl.setInstallAmount(busMaterial.getInstallPrice().multiply(busMaterialPlan100.getCostQuantity100().add(busMaterial.getInstallPrice().multiply(busMaterialPlan100.getCostQuantity200()))));//成本安装费
//            newl.setInstallAmount1(busMaterial.getInstallPrice1().multiply(busMaterialPlan100.getCostQuantity100().add(busMaterial.getInstallPrice1().multiply(busMaterialPlan100.getCostQuantity200()))));
//            newl.setInstallAmount2(busMaterial.getInstallPrice2().multiply(busMaterialPlan100.getCostQuantity100().add(busMaterial.getInstallPrice2().multiply(busMaterialPlan100.getCostQuantity200()))));
//            newl.setInstallAmount3(busMaterial.getInstallPrice3().multiply(busMaterialPlan100.getCostQuantity100().add(busMaterial.getInstallPrice3().multiply(busMaterialPlan100.getCostQuantity200()))));
//            newl.setSyntheticalPrice1(busMaterial.getSyntheticalPrice1());//有合同综合价
//            newl.setSyntheticalPrice2(busMaterial.getSyntheticalPrice2());//拟合同综合价
//            newl.setSyntheticalPrice3(busMaterial.getSyntheticalPrice3());//合同综合价
//            newl.setSyntheticalPrice(busMaterial.getSyntheticalPrice()//预算成本综合价
//            newl.setMainsumPrice1(busMaterial.getMainsumPrice1());
//            newl.setMainsumPrice2(busMaterial.getMainsumPrice2());
//            newl.setMainsumPrice3(busMaterial.getMainsumPrice3());
//            newl.setInstallsumPrice1(busMaterial.getInstallsumPrice1());
//            newl.setInstallsumPrice2(busMaterial.getInstallsumPrice2());
//            newl.setInstallsumPrice3(busMaterial.getInstallsumPrice3());
//            newl.setContractsumSyntheticalPrice1(
//                busMaterial.getMainsumPrice1().multiply(busMaterialPlan100.getCostQuantity100()
//                    .add(busMaterial.getMainsumPrice1().multiply(busMaterialPlan100.getCostQuantity200())))
//                    .add( busMaterial.getInstallsumPrice1().multiply(busMaterialPlan100.getCostQuantity100()
//                        .add(busMaterial.getInstallsumPrice1().multiply(busMaterialPlan100.getCostQuantity200())))));
//            newl.setContractsumSyntheticalPrice2(
//                busMaterial.getMainsumPrice2().multiply(busMaterialPlan100.getCostQuantity100()
//                    .add(busMaterial.getMainsumPrice2().multiply(busMaterialPlan100.getCostQuantity200())))
//                    .add( busMaterial.getInstallsumPrice2().multiply(busMaterialPlan100.getCostQuantity100()
//                        .add(busMaterial.getInstallsumPrice2().multiply(busMaterialPlan100.getCostQuantity200()))))
//            );
//            newl.setContractsumSyntheticalPrice3(
//                busMaterial.getMainsumPrice3().multiply(busMaterialPlan100.getCostQuantity100()
//                    .add(busMaterial.getMainsumPrice3().multiply(busMaterialPlan100.getCostQuantity200())))
//                    .add( busMaterial.getInstallsumPrice3().multiply(busMaterialPlan100.getCostQuantity100()
//                        .add(busMaterial.getInstallsumPrice3().multiply(busMaterialPlan100.getCostQuantity200()))))
//            );
            bBusMaterialList.add(newl);
            //修正版本信息
            busMaterialPlan100.setMaterialId(materialId);
            busMaterialPlan100.setVersionId(versionId);
            busMaterialPlan100.setCreateTime(DateUtils.getNowDateTime());
            busMaterialPlan100.setUpdateTime(null);
            busMaterialPlan100.setApplayStatus(ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);//待审核状态
            busMaterialPlan100.setVersionStatus(0);//临时版本
            if(FlymeUtils.isNotEmpty(map.get("planType"))){
                busMaterialPlan100.setPlanType(Integer.parseInt(map.get("planType").toString()));
            }
            if (FlymeUtils.isNotEmpty(busMaterialPlan100.getParentId())) {
                busMaterialPlan100.setParentId(busMaterialPlan100.getParentId());
            } else {
                busMaterialPlan100.setParentId(busMaterialPlan100.getMaterialPlanId());
            }
            Long parentId1 = busMaterialPlan100.getParentId();
            String packageNo = busMaterialPlan100.getPackageNo();
            String redisKey = "plan100_" + parentId1;
            String levelNo = levelNoUtil.getLevelNo(redisKey, packageNo, busMaterialPlan100.getLevelNo());
            busMaterialPlan100.setLevelNo(levelNo);
            busMaterialPlan100.setMaterialPlanId(IdWorker.getId());
        }
        if (busMaterialPlan100List.size() > 0) {
            saveBatch(busMaterialPlan100List);
            busMaterialService.saveBatch(bBusMaterialList);
        }
        return ResultBody.ok();
    }

    @Override
    public ResultBody mergeplan100(Map map) {
        Long projectId = FlymeUtils.getLong(map.get("projectId"));
        BusProject project = busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        String userName = OpenHelper.getUserName();
        Integer type = TypeUtils.castToInt(map.get("dataType"));
        // 设定请求MAP
        pmsApiUtil.setPlanPackageDataToReqMap(map, projectId, null, null, type, type == 1 ? ApiConstants.ENGINEER_APPROVAL_WZ_100_UPD : ApiConstants.ENGINEER_APPROVAL_WZ_100_ADD);
        int approvalResult = 0;
        if (type == 1) {
            approvalResult = syncOAService.approval(map, "/approvl/bmep100UpdateDetail", userName, ApiConstants.ENGINEER_APPROVAL_WZ_100_UPD, projectId.toString());
        }
        if (type == 2) {
            approvalResult = syncOAService.approval(map, "/approvl/bmep100AddDetail", userName, ApiConstants.ENGINEER_APPROVAL_WZ_100_ADD, projectId.toString());
        }
        if (ApiConstants.APPROVAL_SUCCESS == approvalResult) {
            //修改状态为 审核中
            updateApplayStatus(projectId, type, ApiConstants.WZ_APPLYSTATUS_AUDIT_ING);
            return ResultBody.ok("OA审批提交成功");
        } else {
            updateApplayStatus(projectId, type, ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);
            return ResultBody.failed("OA审批提交失败");
        }

    }
    @Override
    public ResultBody goMerge100( Integer checkState ,Long projectId) throws Exception {
        //更新数据为审核成功
//        goApplyStatus(projectId,2);
        if (checkState == ApiConstants.APPROVAL_SUCCESS) {
            //审核通过
            Boolean b = pmaOaUtil.updateMaterialBase(projectId, ApiConstants.VER_100, ApiConstants.INT_ZERO);
            if (b) {
                //将审核通过的新增的数据，属于父节点的，版本改为正式版本
                CriteriaUpdate<BusMaterialPlan100> cu = new CriteriaUpdate<BusMaterialPlan100>();
                cu.eq("projectId", projectId);
                cu.eq("applayStatus", ApiConstants.WZ_APPLYSTATUS_AUDIT_PASS);
                cu.eq("versionStatus", 0);
                cu.eq("parentId", 0);
                cu.set("versionStatus", ApiConstants.INT_ONE);
                cu.set("parentId", null);
                update(cu);
                return ResultBody.ok("合并子节点成功");
            }
        }
        return ResultBody.failed("合并子节点失败");
    }

    @Override
    public Boolean updateApplayStatus(Long projectId, Integer planType, Integer applayStatus) {
        List<String> majorCodes=busMajorService.getUserMajors(OpenHelper.getUserId());
        CriteriaUpdate<BusMaterialPlan100> cu = new CriteriaUpdate<>();
        cu.eq("projectId", projectId);
        cu.eq("planType", planType);
        cu.eq("versionStatus", 0);
        //提交之前的数据都叫待审核，只需要修改这部分的数据
        cu.eq("applayStatus", ApiConstants.WZ_APPLYSTATUS_AUDIT_WAIT);
        if (majorCodes.size() > 0) {
            if (!majorCodes.contains("P99")) {
                cu.in("majorCode",majorCodes);
            }
        }
        cu.set("applayStatus", applayStatus);
        return update(cu);
    }

    @Override
    public Boolean goApplyStatus(Long projectId, Integer applayStatus) {
        CriteriaUpdate<BusMaterialPlan100> cu = new CriteriaUpdate<>();
        cu.eq("projectId", projectId);
        cu.eq("applayStatus", "1");//审核中的状态
        cu.eq("versionStatus", 0);
        cu.set("applayStatus", applayStatus);
        cu.set("versionStatus", 1);
        return update(cu);
    }
    @Override
    public List<EntityMap> selectInnerOrder(Long purchaseId, Long materialPlanId) {
        CriteriaQuery cq = new CriteriaQuery<>(BusMaterialPlan100.class);
        cq.select("bmss.busMaterialSrmSubId,bmss.materialPlanId,bmss.contractNo,bmss.orderQty,bmss.orderOutQty,bmss.orderThisTimeQty");
//        cq.createJoin(BusPurchaseDetails.class).setMainField("purchaseDetailsId").setJoinField("purchaseDetailsId");
//        cq.createJoin(BusPurchase.class).setMainAlias("purchase").setJoinField("purchaseId").setMainAlias("bpd").setMainField("purchaseId");
//        cq.createJoin(BusMaterial.class).setMainAlias("material").setMainField("materialId").setMainAlias("bpd").setJoinField("materialId");
        cq.createJoin(BusMaterialSrmSub.class).setMainField("materialPlanId").setJoinField("materialPlanId");
        cq.eq("bmplan.materialPlanId", materialPlanId);
        cq.isNull("purchaseorderId");
        cq.isNull("purchaseorderDetailid");
        return selectEntityMap(cq);
    }

    @Override
    public int totalProjectAndVersionStatus(Long projectId, Integer versionStatus) {
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery(BusMaterialPlan100.class);
        cq.eq("projectId", projectId);
        cq.eq("versionStatus", versionStatus);
        return count(cq);
    }

    @Override
    public List<EntityMap> selectVersionList(Map map) {
        String versionType = (String) map.get("versionType");
        CriteriaQuery<BusMaterialPlan100> cq = new CriteriaQuery(BusMaterialPlan100.class);
        cq.select(BusVersion.class, "versionId", "concat(bigVersion,'.',smallVerion) as versionNo");
        cq.eq("bmplan.projectId", map.get("projectId"));
        cq.isNotNull("version.versionId");
        if ("1".equals(versionType)) {
            cq.eq("version.bigVersion", "100");
            cq.ne("version.smallVerion", "00");
        }
        if ("2".equals(versionType)) {
            cq.ne("version.bigVersion", "100");
        }
        cq.createJoin(BusVersion.class).setMainField("versionId").setJoinField("versionId");
        cq.groupBy("bmplan.versionId");
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody transferedVersion(Long[] materialPlanIds, Long PojectId) {
        EntityMap entityMap = new EntityMap();
        entityMap.put("projectId", PojectId);
        BusProject project = busProjectService.getById(PojectId);
        if (FlymeUtils.isEmpty(project)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = project.getState();
        if (state != null && state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        int totalCount = totalProjectAndVersionStatus(project.getProjectId(), 0);
        if (totalCount > 0) {
            return ResultBody.failed("有需要合并的数据，暂不支持转200");
        }
        List<Long> getPlanIds = getPlanIds(PojectId);
        List<BusMaterialPlan100> list_100s = Lists.newArrayList();
        for (Long id : getPlanIds) {
            BusMaterialPlan100 p_100 = getById(id);
            p_100.setStatus(2);//状态为2为已转200版本
            list_100s.add(p_100);
        }
        if (FlymeUtils.isNotEmpty(getPlanIds)) {
            entityMap.put("materialPlanIds", getPlanIds);
        }
        List<EntityMap> lists = busMaterialMapper.sumplanDetail(entityMap);
        //转存200oa 调用
        int status= syncOAService.approval(lists, "/approvl/bmepDetail", OpenHelper.getUserName(), ApiConstants.BUSINESS_APPROVAL_WZ_100 ,PojectId.toString());
        if(status==1){
            project.setState(1);
            busProjectService.saveOrUpdate(project);//更新项目为锁定状态
            return ResultBody.ok("数据已请求，等待是审批");
        }
        return ResultBody.ok();
    }
    @Override
    public ResultBody goVersion200(Integer checkState, Long projectId) {
        EntityMap entityMap = new EntityMap();
        entityMap.put("projectId", projectId);
        BusProject project = busProjectService.getById(projectId);
        if (checkState == ApiConstants.APPROVAL_REJECT) {//审核驳回
            ResultBody resultBody = busProjectService.updateProjectStus(projectId, 0);
            resultBody.setMsg("审批驳回,项目状态已更为正常");
            return resultBody;
        }
        //审批通过
        if (checkState == ApiConstants.APPROVAL_SUCCESS) {
            List<Long> getPlanIds = getPlanIds(projectId);
            List<BusMaterialPlan100> list_100s = Lists.newArrayList();
            for (Long id : getPlanIds) {
                BusMaterialPlan100 p_100 = getById(id);
                p_100.setStatus(2);//状态为2为已转200版本
                list_100s.add(p_100);
            }
            if (FlymeUtils.isNotEmpty(getPlanIds)) {
                entityMap.put("materialPlanIds", getPlanIds);
            }
            List<EntityMap> lists = busMaterialMapper.sumplanDetail(entityMap);
            BusVersion latestVersion = busVersionService.getLatestVersion(projectId, 1);
            if (FlymeUtils.isEmpty(latestVersion)) {
                return ResultBody.failed("无版本信息");
            }
            Long versionId = IdWorker.getId();
            BusVersion newBusVersion = new BusVersion();
            newBusVersion.setBigVersion("200");
            newBusVersion.setSmallVerion("00");
            newBusVersion.setVersionType(1);
            newBusVersion.setState(1);
            newBusVersion.setUserId(OpenHelper.getUserId());
            newBusVersion.setVersionId(versionId);
            newBusVersion.setProjectId(projectId);
            project.setVersionId(versionId);
            project.setUserId(OpenHelper.getUserId());
            newBusVersion.setCreateTime(DateUtils.getNowDateTime());
            if (FlymeUtils.isNotEmpty(lists)) {
                List<BusMaterial> materials = new ArrayList<>();
                List<BusMaterialPlan200> plan200s = new ArrayList<>();
                for (EntityMap ste : lists) {
                    Long id = IdWorker.getId();
                    BusMaterial material = new BusMaterial();
                    BeanUtils.copyProperties(ste, material);
                    material.setMaterialId(id);
                    material.setProjectId(projectId);
                    BusMaterialPlan200 busplan200 = new BusMaterialPlan200();
                    BeanUtils.copyProperties(ste, busplan200);
                    busplan200.setMaterialId(id);
                    busplan200.setMaterialPlanId(IdWorker.getId());
                    busplan200.setVersionId(versionId);
                    busplan200.setProjectId(project.getProjectId());
                    busplan200.setCostQuantity200(ste.getBigDecimal("costQuantity100"));
                    busplan200.setCostdisplayQuantity200(ste.getBigDecimal("costQuantity100"));
                    busplan200.setCostQuantity100(ste.getBigDecimal("costQuantity100"));
                    busplan200.setOrderflg(ste.get("orderflg"));//初始化开口订单状态
                    busplan200.setMajorName(ste.get("majorName"));
                    busplan200.setMajorCode(ste.get("majorCode"));
                    busplan200.setPackageName(ste.get("projectName"));
                    busplan200.setPackageNo(ste.get("projectCode"));
                    busplan200.setMaterialWbsCode(ste.get("materialWbsCode"));
                    busplan200.setMaterialName(ste.get("materialName"));
                    busplan200.setMaterialCode(ste.get("materialCode"));
                    busplan200.setSubjectName(ste.get("subjectName"));
                    busplan200.setContractDesc(ste.get("contractDesc"));
                    busplan200.setMaterialArea(ste.get("materialArea"));
                    busplan200.setMaterialUse(ste.get("materialUse"));
                    busplan200.setPackageName(ste.get("packageName"));
                    busplan200.setPackageNo(ste.get("packageNo"));
                    busplan200.setLevelNo(ste.get("levelNo"));
                    busplan200.setContractMainPrice1(ste.getBigDecimal("contractMainPrice1"));
                    busplan200.setContractMainPrice2(ste.getBigDecimal("contractInstallPrice2"));
                    busplan200.setContractMainPrice3(ste.getBigDecimal("contractInstallPrice3"));
                    busplan200.setMeasurementUnit(ste.get("measurementUnit"));
                    busplan200.setBrandName(ste.get("brandName"));
                    busplan200.setRemark(ste.get("remark"));
                    busplan200.setLoss(ste.getBigDecimal("planloss"));
                    busplan200.setTechnicalData(ste.get("technicalData"));
                    busplan200.setMateriaSpecs(ste.get("materiaSpecs"));
                    busplan200.setZtPurchaseCount(ste.getBigDecimal("ztPurchaseCount"));
                    busplan200.setDhPurchaseCount(ste.getBigDecimal("endPurchaseCount"));
                    busplan200.setPurchaseCount(ste.getBigDecimal("purchaseCount"));
                    busplan200.setOrderflg("0");
                    busplan200.setPlanPurchaseCount(ste.getBigDecimal("plancgCount"));
                    busplan200.setDisplayplanPurchaseCount(ste.getBigDecimal("plancgCount"));
                    busplan200.setEndPurchaseCount(ste.getBigDecimal("endPurchaseCount"));
                    busplan200.setStatus("2");//节点2
                    busplan200.setPackagePlan100Id(ste.getLong("materialPlanId")); // 100计划关联主key
                    material.setSyntheticalAmount(ste.getBigDecimal("syntheticalAmount"));
                    material.setSyntheticalAmount1(ste.getBigDecimal("syntheticalAmount1"));
                    material.setSyntheticalAmount2(ste.getBigDecimal("syntheticalAmount2"));
                    material.setSyntheticalAmount3(ste.getBigDecimal("syntheticalAmount3"));
                    material.setContractsumSyntheticalPrice1(ste.getBigDecimal("contractsumSyntheticalPrice1"));
                    material.setContractsumSyntheticalPrice2(ste.getBigDecimal("contractsumSyntheticalPrice2"));
                    material.setContractsumSyntheticalPrice3(ste.getBigDecimal("contractsumSyntheticalPrice3"));
                    material.setInstallAmount(ste.getBigDecimal("installAmount"));
                    material.setInstallAmount1(ste.getBigDecimal("installAmount1"));
                    material.setInstallAmount2(ste.getBigDecimal("installAmount2"));
                    material.setInstallAmount3(ste.getBigDecimal("installAmount3"));
                    material.setMainsumPrice1(ste.getBigDecimal("mainsumPrice1"));
                    material.setMainsumPrice2(ste.getBigDecimal("mainsumPrice2"));
                    material.setMainsumPrice3(ste.getBigDecimal("mainsumPrice3"));
                    material.setInstallsumPrice1(ste.getBigDecimal("installsumPrice1"));
                    material.setInstallsumPrice2(ste.getBigDecimal("installsumPrice2"));
                    material.setInstallsumPrice3(ste.getBigDecimal("installsumPrice3"));
                    material.setMainAmount(ste.getBigDecimal("mainAmountum"));
                    material.setMainAmount1(ste.getBigDecimal("mainAmount1"));
                    material.setMainAmount2(ste.getBigDecimal("mainAmount2"));
                    material.setMainAmount3(ste.getBigDecimal("mainAmount3"));
                    material.setConversionUnit(ste.get("conversionUnit"));
                    material.setMeasurementUnit(ste.get("measurementUnit"));
                    material.setMainPrice(ste.getBigDecimal("mainPrice"));
                    material.setMainPrice1(ste.getBigDecimal("mainPrice1"));
                    material.setMainPrice2(ste.getBigDecimal("mainPrice2"));
                    material.setMainPrice3(ste.getBigDecimal("mainPrice3"));
                    material.setInstallPrice(ste.getBigDecimal("contractInstallPrice"));
                    material.setInstallPrice1(ste.getBigDecimal("contractInstallPrice1"));
                    material.setInstallPrice2(ste.getBigDecimal("contractInstallPrice2"));
                    material.setSyntheticalPrice1(ste.getBigDecimal("syntheticalPrice1"));//有合同综合价
                    material.setSyntheticalPrice2(ste.getBigDecimal("syntheticalPrice2"));//拟合同综合价
                    material.setSyntheticalPrice3(ste.getBigDecimal("syntheticalPrice3"));//合同综合价
                    material.setSyntheticalPrice(ste.getBigDecimal("syntheticalPrice"));//预算成本综合价
                    material.setContractBillQuantity(ste.getBigDecimal("contractBillQuantity"));
                    material.setLoss(ste.getBigDecimal("loss"));
                    material.setPlanPurchaseCount(ste.getBigDecimal("costQuantity100").multiply(ste.getBigDecimal("planloss")));
                    material.setTotalFinishCount(BigDecimal.ZERO);
                    material.setCurrentFinishMonthCount(BigDecimal.ZERO);
                    material.setLastFinishMonthCount(BigDecimal.ZERO);
                    material.setParentId(0L);
                    material.setCurrentMonthmainPrice(BigDecimal.ZERO);
                    material.setCurrentMonthinstallPrice(BigDecimal.ZERO);
                    material.setCurrentMonthsumPrice(BigDecimal.ZERO);
                    material.setLastMonthinstallPrice(BigDecimal.ZERO);
                    material.setLastMonthmainPrice(BigDecimal.ZERO);
                    material.setLastMonthsumPrice(BigDecimal.ZERO);
                    material.setTotalsumPrice(BigDecimal.ZERO);
                    material.setTotalMonthinstallPrice(BigDecimal.ZERO);
                    material.setTotalMonthmainPrice(BigDecimal.ZERO);
                    materials.add(material);
                    plan200s.add(busplan200);
                }
                project.setState(0);//正常状态
                busMaterialService.saveBatch(materials);
                busMaterialPlan200Service.saveBatch(plan200s);
                busProjectService.saveOrUpdate(project);
                busVersionService.save(newBusVersion);
                if (FlymeUtils.isNotEmpty(list_100s)) {
                    updateBatchById(list_100s);//更新原100数据状态为200版本
                }
            }
        }
        return ResultBody.ok();
      }


}
